package com.bestcem.xm.member.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bestcem.xm.member.controller.dto.HttpImportRecordDTO;
import com.bestcem.xm.member.controller.vo.ExtendFieldVO;
import com.bestcem.xm.member.controller.vo.MemberVO;
import com.bestcem.xm.member.entity.mongo.ExtendFieldValue;
import com.bestcem.xm.member.entity.mysql.LabelValueId;
import com.bestcem.xm.member.entity.pojo.*;
import com.bestcem.xm.member.enums.ExtendFieldTypeEnum;
import com.bestcem.xm.member.grpc.service.param.project.CreateProjectParam;
import com.bestcem.xm.member.grpc.service.param.project.UpdateProjectParam;
import com.bestcem.xm.member.service.dto.*;
import com.bestcem.xm.member.util.MemberUtil;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * service do 换Dto
 *
 * @author yf.wang <yf.wang@idiaoyan.com>
 * @version V1.0
 * @date 2021/9/15
 */
public class ConvertUtil {

    public static HttpImportRecordDTO importRecordDoToHttpImportRecordDTO(ImportRecordDo importRecordEntity) {
        HttpImportRecordDTO dto = new HttpImportRecordDTO();
        dto.setCreateTime(importRecordEntity.getCreatedTime());
        dto.setFileName(importRecordEntity.getFileName());
        dto.setId(importRecordEntity.getId());
        dto.setMType(importRecordEntity.getMemberType());
        dto.setOrgId(importRecordEntity.getOrgId());
        dto.setStatus(importRecordEntity.getStatus());
        dto.setUserId(importRecordEntity.getOpUserId());
        return dto;
    }

    /**
     * 构造联系人详情数据
     *
     * @param isDisplayContact 是否隐藏联系信息
     * @param member
     * @return
     */
    public static MemberDTO parseMember(boolean isDisplayContact, MemberDO member) {
        // 将 entity 复制 到 dto
        MemberDTO dto = memberDoToMemberDto(member);
        List<ExtendFieldValue> fieldValList = JSONObject.parseArray(member.getFieldValList(), ExtendFieldValue.class);
        List<LabelValueId> labels = JSONObject.parseArray(member.getLabels(), LabelValueId.class);
        if (CollUtil.isNotEmpty(labels)) {
            List<LabelValueIdDTO> labelValueIds = labels.stream().map(label -> {
                LabelValueIdDTO dto1 = new LabelValueIdDTO();
                dto1.setId(label.getId());
                dto1.setLabelId(label.getLabelId());
                return dto1;
            }).collect(Collectors.toList());
            dto.setLabelValueIds(labelValueIds);
        }
        // 根据可见范围 处理返回值的手机号和邮箱隐藏敏感信息
        dto.setMobile(MemberUtil.handleMobile(dto.getMobile(), isDisplayContact));
        dto.setEmail(MemberUtil.handleEmail(dto.getEmail(), isDisplayContact));

        if (CollectionUtil.isNotEmpty(fieldValList)) {
            List<ExtendFieldDTO> newFieldValList = fieldValList.stream().map(field -> {
                ExtendFieldDTO extendFieldDTO = new ExtendFieldDTO();
                extendFieldDTO.setValue(Optional.ofNullable(field.getFieldValue()).orElse("").toString());
                extendFieldDTO.setId(field.getFieldId());
                extendFieldDTO.setName(field.getFieldName());
                extendFieldDTO.setType(field.getFieldType());
                // 扩展字段值
                String value = Optional.ofNullable(field.getFieldValue()).orElse("").toString();
                if (StrUtil.isEmpty(value)) {
                    // 若没有值，则跳过
                    return extendFieldDTO;
                }
                // 获取扩展字段类型
                Integer type = field.getFieldType();
                // 获取扩展字段值
                switch (ExtendFieldTypeEnum.getByIndex(type)) {
                    case DATETIME:
                        DateTime parse = DateUtil.parse(value);
                        extendFieldDTO.setValue(parse.toString("yyyy/MM/dd"));
                        break;
                    // 扩展标签进行隐藏手机和邮箱的处理
                    case MOBILE:
                        extendFieldDTO.setValue(MemberUtil.handleMobile(extendFieldDTO.getValue(), isDisplayContact));
                        break;
                    case EMAIL:
                        extendFieldDTO.setValue(MemberUtil.handleEmail(extendFieldDTO.getValue(), isDisplayContact));
                        break;
                }
                return extendFieldDTO;
            }).collect(Collectors.toList());
            dto.setFieldValList(newFieldValList);
        }

        List<ExtendFieldDTO> fieldValList1 = dto.getFieldValList();
        if (CollUtil.isNotEmpty(fieldValList1)) {
            List<Map<String, JSONObject>> fields = new ArrayList<>();
            fieldValList1.forEach(f -> {
                Map<String, JSONObject> map = new HashMap<>();
                JSONObject object = (JSONObject) JSON.toJSON(f);
                object.put("attribute", member.getMemberType());
                map.put(f.getId(), object);
                fields.add(map);
            });
            dto.setFields(fields);
        }
        return dto;
    }

    public static MemberDTO memberDoToMemberDto(MemberDO member) {
        MemberDTO dto = new MemberDTO();
        dto.setId(member.getId());
        dto.setOrgId(member.getOrgId());
        dto.setSysId(member.getSysId());
        dto.setSource(member.getSource());
        dto.setName(member.getName());
        dto.setEmail(member.getEmail());
        dto.setMobile(member.getPhone());
        dto.setGender(member.getGender());
        dto.setStore(member.getStoreId());
        dto.setStatus(member.getStatus());
        dto.setContent(member.getContent());
        dto.setOpenId(member.getOpenId());
        dto.setNickname(member.getNickname());
        dto.setAppId(member.getAppId());
        dto.setAlipayUserId(member.getAliPayUserId());
        dto.setMemberNo(member.getMemberNo());
        if (StrUtil.isNotEmpty(member.getAddress())) {
            dto.setAddress(JSONObject.parseArray(member.getAddress(), String.class));
        } else {
            dto.setAddress(new ArrayList<>());
        }
        dto.setEmployeeId(member.getEmployeeId());
        dto.setEmployeeStatus(member.getEmployeeStatus());
        dto.setMemberType(member.getMemberType());
        dto.setBirthday(member.getBirthday());
        dto.setDepartment(member.getDepartment());
        dto.setPosition(member.getPosition());
        dto.setInstituteId(member.getInstituteId());
        dto.setInstituteName(member.getInstituteName());
        dto.setUserId(member.getUserId());
        dto.setAge(member.getAge());
        dto.setRegion(member.getRegion());
        dto.setCreateTime(member.getCreateTime());
        dto.setUpdateTime(member.getUpdateTime());
        dto.setOutNo(member.getOutNo());
        return dto;
    }

    /**
     * do 转 vo
     * @param member
     * @return
     */
    public static MemberVO memberDoToMemberVo(MemberDO member) {
        MemberVO vo = new MemberVO();
        vo.setId(member.getId());
        vo.setOrgId(member.getOrgId());
        vo.setSysId(member.getSysId());
        vo.setSource(member.getSource());
        vo.setName(member.getName());
        vo.setNickname(member.getNickname());
        vo.setEmail(member.getEmail());
        vo.setMobile(member.getPhone());
        vo.setGender(member.getGender());
        vo.setStore(member.getStoreId());
        vo.setStatus(member.getStatus());
        vo.setContent(member.getContent());
        vo.setOpenId(member.getOpenId());
        vo.setAppId(member.getAppId());
        vo.setUnionId(member.getUnionId());
        vo.setAvatar(member.getAvatar());
        vo.setAlipayUserId(member.getAliPayUserId());
        vo.setMemberNo(member.getMemberNo());
        if (StrUtil.isNotEmpty(member.getAddress())) {
            vo.setAddress(JSONObject.parseArray(member.getAddress(), String.class));
        } else {
            vo.setAddress(new ArrayList<>());
        }
        vo.setEmployeeId(member.getEmployeeId());
        vo.setEmployeeStatus(member.getEmployeeStatus());
        vo.setMemberType(member.getMemberType());
        vo.setBirthday(member.getBirthday());
        vo.setDepartment(member.getDepartment());
        vo.setPosition(member.getPosition());
        vo.setInstituteId(member.getInstituteId());
        vo.setInstituteName(member.getInstituteName());
        vo.setUserId(member.getUserId());
        vo.setAge(member.getAge());
        vo.setCreateTime(member.getCreateTime());
        vo.setUpdateTime(member.getUpdateTime());
        vo.setOutNo(member.getOutNo());
        return vo;
    }

    public static ExtendFieldVO extendFieldDO2ExtendFieldVO(ExtendFieldDO extendFieldDO) {
        if (extendFieldDO == null) {
            return new ExtendFieldVO();
        }
        ExtendFieldVO extendFieldVO = new ExtendFieldVO();
        extendFieldVO.setCreateTime(extendFieldDO.getCreateTime());
        extendFieldVO.setId(extendFieldDO.getFieldId());
        extendFieldVO.setMemberType(extendFieldDO.getMemberType());
        extendFieldVO.setName(extendFieldDO.getName());
        extendFieldVO.setOrgId(extendFieldDO.getOrgId());
        extendFieldVO.setType(extendFieldDO.getType());
        extendFieldVO.setUpdateTime(extendFieldDO.getUpdateTime());
        return extendFieldVO;
    }

    public static ProjectDO createProjectParam2ProjectDo(CreateProjectParam param) {
        if (param == null) {
            return new ProjectDO();
        }
        ProjectDO projectDo = new ProjectDO();
        projectDo.setCode(param.getCode());
        projectDo.setName(param.getName());
        projectDo.setContractNo(param.getContractNo());
        projectDo.setContractObj(param.getContractObj());
        projectDo.setMemberId(param.getMemberId());
        projectDo.setOrgId(param.getOrgId());
        projectDo.setProjectManager(param.getProjectManager());
        projectDo.setType(param.getType());
        projectDo.setAcceptanceTime(param.getAcceptanceTime());
        projectDo.setAccountManager(param.getAccountManager());
        projectDo.setActualStartTime(param.getActualStartTime());
        projectDo.setContractMoney(param.getContractMoney());
        projectDo.setProgramStartTime(param.getProgramStartTime());
        projectDo.setProjectManagerPhone(param.getProjectManagerMobile());
        projectDo.setProjectTime(param.getProjectTime());
        projectDo.setStatus(param.getStatus());
        return projectDo;
    }

    public static ProjectDto projectDO2ProjectDto(ProjectDO projectDO) {
        if (projectDO == null) {
            return new ProjectDto();
        }

        ProjectDto dto = new ProjectDto();
        dto.setProjectManagerMobile(projectDO.getProjectManagerPhone());
        dto.setProjectManager(projectDO.getProjectManager());
        dto.setAccountManager(projectDO.getAccountManager());
        dto.setAcceptanceTime(projectDO.getAcceptanceTime());
        dto.setActualStartTime(projectDO.getActualStartTime());
        dto.setCode(projectDO.getCode());
        dto.setContractMoney(projectDO.getContractMoney());
        dto.setContractNo(projectDO.getContractNo());
        dto.setContractObj(projectDO.getContractObj());
        // dto.setEndTime();
        dto.setId(projectDO.getProjectId());
        dto.setMemberId(projectDO.getMemberId());
        dto.setName(projectDO.getName());
        dto.setOrgId(projectDO.getOrgId());
        dto.setProgramStartTime(projectDO.getProgramStartTime());
        dto.setProjectTime(projectDO.getProjectTime());
        dto.setStatus(projectDO.getStatus());
        dto.setType(projectDO.getType());
        return dto;
    }

    public static ProjectDO updateProjectParam2ProjectDo(UpdateProjectParam param) {
        if (param == null) {
            return new ProjectDO();
        }
        ProjectDO projectDo = new ProjectDO();
        projectDo.setProjectId(param.getId());
        projectDo.setCode(param.getCode());
        projectDo.setName(param.getName());
        projectDo.setContractNo(param.getContractNo());
        projectDo.setContractObj(param.getContractObj());
        projectDo.setMemberId(param.getMemberId());
        projectDo.setOrgId(param.getOrgId());
        projectDo.setProjectManager(param.getProjectManager());
        projectDo.setType(param.getType());
        projectDo.setAcceptanceTime(param.getAcceptanceTime());
        projectDo.setAccountManager(param.getAccountManager());
        projectDo.setActualStartTime(param.getActualStartTime());
        projectDo.setContractMoney(param.getContractMoney());
        projectDo.setProgramStartTime(param.getProgramStartTime());
        projectDo.setProjectManagerPhone(param.getProjectManagerMobile());
        projectDo.setProjectTime(param.getProjectTime());
        projectDo.setStatus(param.getStatus());
        if (!CollectionUtils.isEmpty(param.getExtendFieldValues())) {
            List<ExtendFieldValue> values = new ArrayList<>();
            param.getExtendFieldValues().stream().forEach( value -> {
                ExtendFieldValue res = new ExtendFieldValue();
                res.setFieldId(value.getId());
                res.setFieldType(value.getType());
                res.setFieldName(value.getName());
                res.setFieldValue(value.getValue());
                values.add(res);
            });
            projectDo.setFieldValList(JSONObject.toJSONString(values));
        } else {
            projectDo.setFieldValList(JSONObject.toJSONString(new ArrayList<>()));
        }
        return projectDo;
    }

    public static ExtendFieldEnumItemDto extendFieldEnumItemDO2ExtendFieldEnumItemDto(ExtendFieldEnumItemDO enumItem) {
        if (enumItem == null) {
            return new ExtendFieldEnumItemDto();
        }
        ExtendFieldEnumItemDto dto = new ExtendFieldEnumItemDto();
        dto.setId(enumItem.getFieldEnumId());
        dto.setDeleteStatus(enumItem.getDeleteStatus());
        dto.setDisplayStatus(enumItem.getDisplayStatus());
        dto.setExtendFieldId(enumItem.getExtendFieldId());
        dto.setName(enumItem.getName());
        dto.setSerial(enumItem.getSeq());
        return dto;
    }

}
